<template>
  <view class="media-upload">
    <!-- 媒体预览区域 -->
    <view class="preview-area" v-if="modelValue">
      <image
        v-if="mediaType === 'image'"
        :src="modelValue"
        class="preview-image"
        mode="aspectFill"
      />
      <video
        v-else-if="mediaType === 'video'"
        :src="modelValue"
        class="preview-video"
      />
      <view class="delete-btn" @tap="handleDelete">×</view>
    </view>

    <!-- 上传按钮区域 -->
    <view v-else class="upload-buttons">
      <view class="upload-btn" @tap="chooseImage">
        <image src="/static/images/icon/image.png" class="upload-icon" />
        <text>图片</text>
      </view>
      <view class="upload-btn" @tap="chooseVideo">
        <image src="/static/images/icon/video.png" class="upload-icon" />
        <text>视频</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 获取环境变量中的基础 API 地址
const baseApi = import.meta.env.VITE_APP_BASE_API

// 定义组件的属性
const props = defineProps({
  modelValue: String,    // 媒体文件的URL
  mediaType: String,     // 媒体类型：'image' 或 'video'
  maxSize: {            // 最大文件大小（MB）
    type: Number,
    default: 10
  },
  token: {
    type: String,
    default: ''
  }
})

// 定义组件的事件
const emit = defineEmits(['update:modelValue', 'update:mediaType'])
const loginResult = uni.getStorageSync('loginResult')
const token = loginResult.accessToken

// 选择图片
const chooseImage = async () => {
  try {
    console.log('当前token:', uni.getStorageSync('accessToken'))
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })

    // 检查文件大小
    const tempFilePath = res.tempFilePaths[0]
    const fileInfo = await uni.getFileInfo({
      filePath: tempFilePath
    })

    if (fileInfo.size > props.maxSize * 1024 * 1024) {
      uni.showToast({
        title: `图片大小不能超过${props.maxSize}MB`,
        icon: 'none'
      })
      return
    }

    // 上传文件
    await uploadFile(tempFilePath, 'image')
  } catch (error) {
    console.error('选择图片失败:', error)
    uni.showToast({
      title: '选择图片失败',
      icon: 'none'
    })
  }
}

// 选择视频
const chooseVideo = async () => {
  try {
    const res = await uni.chooseVideo({
      compressed: true,
      maxDuration: 60,
      sourceType: ['album', 'camera']
    })

    // 检查文件大小
    if (res.size > props.maxSize * 1024 * 1024) {
      uni.showToast({
        title: `视频大小不能超过${props.maxSize}MB`,
        icon: 'none'
      })
      return
    }

    // 上传文件
    await uploadFile(res.tempFilePath, 'video')
  } catch (error) {
    console.error('选择视频失败:', error)
    uni.showToast({
      title: '选择视频失败',
      icon: 'none'
    })
  }
}

// 上传文件
const uploadFile = (filePath, type) => {
  return new Promise((resolve, reject) => {
    uni.showLoading({
      title: '上传中...'
    })

    // 获取token
    if (!token) {
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        content: '请先登录后再上传',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/accountLogin/accountLogin'
            })
          }
        }
      })
      return reject(new Error('未登录'))
    }

    uni.uploadFile({
      url: `${baseApi}/p/social/post/upload`,
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': token
      },
      formData: {
        type
      },
      success: (uploadRes) => {
        uni.hideLoading()
        let result
        try {
          result = typeof uploadRes.data === 'string' ? JSON.parse(uploadRes.data) : uploadRes.data
          console.log('上传响应数据:', result)
        } catch (e) {
          console.error('解析响应数据失败:', e)
          uni.showToast({ title: '服务器返回数据格式错误', icon: 'none' })
          return reject(new Error('服务器返回数据格式错误'))
        }

        if (uploadRes.statusCode === 401) {
          uni.removeStorageSync('accessToken')
          uni.showModal({
            title: '提示',
            content: '登录已过期，请重新登录',
            confirmText: '去登录',
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: '/pages/accountLogin/accountLogin'
                })
              }
            }
          })
          return reject(new Error('认证失败'))
        }

        if (uploadRes.statusCode !== 200 || result.code !== '00000') {
          uni.showToast({ title: result.msg || '上传失败', icon: 'none' })
          return reject(new Error(result.msg || '上传失败'))
        }

        // 获取返回的图片URL
        const fileUrl = result.data
        console.log('文件URL:', fileUrl)

        // 更新父组件的值
        emit('update:modelValue', fileUrl)
        emit('update:mediaType', type)

        // 显示成功提示
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })

        resolve(fileUrl)
      },
      fail: (error) => {
        console.error('上传失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '上传失败，请检查网络',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

// 删除媒体
const handleDelete = () => {
  emit('update:modelValue', '')
  emit('update:mediaType', '')
}

// 清空上传
const clearUpload = () => {
  handleDelete()
}

// 暴露方法给父组件
defineExpose({
  clearUpload
})

onMounted(() => {
  const token = props.token || uni.getStorageSync('accessToken')
  console.log('组件挂载时的 token 状态:', {
    propsToken: props.token,
    storageToken: uni.getStorageSync('accessToken'),
    hasToken: !!token
  })
})
</script>

<style lang="scss" scoped>
.media-upload {
  margin: 20rpx 0;

  .preview-area {
    position: relative;
    width: 100%;
    border-radius: 12rpx;
    overflow: hidden;

    .preview-image {
      width: 100%;
      height: 400rpx;
      object-fit: cover;
    }

    .preview-video {
      width: 100%;
      height: 400rpx;
    }

    .delete-btn {
      position: absolute;
      top: 20rpx;
      right: 20rpx;
      width: 60rpx;
      height: 60rpx;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 30rpx;
      color: #fff;
      font-size: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      &:active {
        opacity: 0.8;
      }
    }
  }

  .upload-buttons {
    display: flex;
    gap: 20rpx;
    padding: 20rpx;
    background-color: #f5f5f5;
    border-radius: 12rpx;

    .upload-btn {
      flex: 1;
      height: 160rpx;
      background-color: #fff;
      border-radius: 12rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      &:active {
        opacity: 0.8;
      }

      .upload-icon {
        width: 60rpx;
        height: 60rpx;
        margin-bottom: 10rpx;
      }

      text {
        font-size: 28rpx;
        color: #666;
      }
    }
  }
}
</style>
